package com.qkbb.admin.kuibu.qkbb.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.weather.LocalWeatherForecastResult;
import com.amap.api.services.weather.LocalWeatherLive;
import com.amap.api.services.weather.LocalWeatherLiveResult;
import com.amap.api.services.weather.WeatherSearch;
import com.amap.api.services.weather.WeatherSearchQuery;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.qkbb.admin.kuibu.R;
import com.qkbb.admin.kuibu.adapter.JoinListAdapter;
import com.qkbb.admin.kuibu.qkbb.JavaBean.Game;
import com.qkbb.admin.kuibu.qkbb.activity.PlayBack;
import com.qkbb.admin.kuibu.qkbb.funcation.HttpPut;
import com.qkbb.admin.kuibu.qkbb.funcation.HttpURLConnHelper;
import com.qkbb.admin.kuibu.qkbb.funcation.ImageDownloadSDCardCacheHelper;
import com.qkbb.admin.kuibu.qkbb.funcation.OSShelp;
import com.qkbb.admin.kuibu.qkbb.funcation.SDCardHelper;
import com.qkbb.admin.kuibu.qkbb.swipemenulistview.SwipeMenu;
import com.qkbb.admin.kuibu.qkbb.swipemenulistview.SwipeMenuCreator;
import com.qkbb.admin.kuibu.qkbb.swipemenulistview.SwipeMenuItem;
import com.qkbb.admin.kuibu.qkbb.swipemenulistview.SwipeMenuListView;
import com.qkbb.admin.kuibu.qkbb.url.Url;
import com.qkbb.admin.kuibu.qkbb.view.CustomProgressDialog;
import com.qkbb.admin.kuibu.qkbb.view.TitleBarView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

public class Foot_fragment_first extends Fragment {
    private String Weatherurl="http://wthrcdn.etouch.cn/WeatherApi?city=";
    private String city;
    private String tagname;
    private String pm25;
    private String quality;
    private TextView pmtextview;
    private SwipeMenuListView listView;
    private List<Game> list;
    private View view;
    private Handler handler;
    private String user_token;
    private JoinListAdapter adapter;
    private RequestQueue queue;
    private StringRequest request;
    private byte[] string;
    private TitleBarView titleBarView;
    private CustomProgressDialog progressDialog;
    private ImageView imageview;
    private LocalWeatherLive weatherlive;
    private TextView textview;
    private int year;
    private int month;
    private int day;
    private String date;
    private SharedPreferences sharedPreferences;
    private TextView steptext;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view=inflater.inflate(R.layout.fragment_foot_fragment_first, container, false);
        progressDialog=CustomProgressDialog.createDialog(getActivity());
        progressDialog.show();
        handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what==0){
                    adapter=new JoinListAdapter(getActivity());
                    adapter.setList(list);
                    listView.setAdapter(adapter);
                    progressDialog. cancel();
                }
            }
        };
        init();
        listView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public void onMenuItemClick(int position, SwipeMenu menu, int index) {
                String data[]={list.get(position).getInstid()};
                String type[]={"instid"};
                new HttpPut(getActivity()).PutData(type, data , Url.PUTEXITGAME);
//                list.clear();
//                getGameist();
//                adapter.setList(list);
//                adapter.notifyDataSetChanged();
                list.remove(position);
                adapter.notifyDataSetChanged();
            }
        });
        getCity();
        return view;
    }
    private void getData() {
        Calendar c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day = c.get(Calendar.DAY_OF_MONTH);
        if (date==null) {
            date = String.valueOf(year) + String.valueOf(month) + String.valueOf(day);
        }
    }
    public void init(){
        list=new ArrayList<Game>();
        getGameist();
        sharedPreferences =getActivity().getSharedPreferences("step",Context.MODE_PRIVATE);
        pmtextview= (TextView) view.findViewById(R.id.textView2);
        listView= (SwipeMenuListView) view.findViewById(R.id.foot_fragment_swipemenulistview);
        titleBarView= (TitleBarView) view.findViewById(R.id.foot_first_titlebar);
        titleBarView.setCenterTexiView("足迹");
        titleBarView.settextColor(Color.WHITE);
        imageview= (ImageView) view.findViewById(R.id.imageView);
        textview= (TextView) view.findViewById(R.id.textView);
        steptext= (TextView) view.findViewById(R.id.steps);
        getData();
        int steps=sharedPreferences.getInt(date,0000);
        String imagename=SDCardHelper.loadFileFromSdCard("imagename",getActivity());
        steptext.setText(steps+"");
        if (imagename!=null){
            String url=new OSShelp(getActivity()).getBitmap(imagename);
            Log.e("imagename", imagename);
            new ImageDownloadSDCardCacheHelper().myDownloadImageSDCardCache(getActivity(),url,imageview,imagename,1);
        }

        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                SwipeMenuItem openitem=new SwipeMenuItem(getActivity());
                openitem.setBackground(R.color.green);
                openitem.setWidth(200);
                openitem.setTitle("退出");
                openitem.setTitleSize(15);
                openitem.setTitleColor(Color.WHITE);
                menu.addMenuItem(openitem);
            }
        };
        listView.setMenuCreator(creator);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), PlayBack.class);
                intent.putExtra("roadid", list.get(position).getRoadid());
                startActivity(intent);
            }
        });
    }
    public List<Game> getGameist(){
        user_token= SDCardHelper.loadFileFromSdCard("user_token",getActivity());
        Log.e("foot",user_token);
        new Thread(new Runnable() {
            @Override
            public void run() {
                string= HttpURLConnHelper.loadByteFromURL(Url.GETROAD + user_token,getActivity());
                if (string!=null){
                    String str=new String(string);
                    Log.e("str",str+" kljsvg");
                    try {
                        JSONObject jsonObject=new JSONObject(str);
                        JSONObject jsonObject1=jsonObject.getJSONObject("data");
                        JSONArray jsonArray=jsonObject1.getJSONArray("UserGameData");
                        for (int i=0;i<jsonArray.length();i++){
                            JSONObject jsonObject2=jsonArray.getJSONObject(i);
                            Game game=new Game();
                            game.setUserid(jsonObject2.getInt("userid"));
                            game.setRoadid(jsonObject2.getInt("roadid"));
                            game.setRoadname(jsonObject2.getString("roadname"));
                            game.setDescription(jsonObject2.getString("description"));
                            game.setPictureurl(jsonObject2.getString("pictureurl"));
                            game.setInstid(jsonObject2.getString("instid"));
                            game.setPreviousidxno(jsonObject2.getInt("previousidxno"));
                            game.setNextidxno(jsonObject2.getInt("nextidxno"));
                            game.setGroupid(jsonObject2.getString("groupid"));
                            game.setNickname(jsonObject2.getString("nickname"));
                            game.setSteps(jsonObject2.getInt("steps"));
                            game.setActivestatus(jsonObject2.getInt("activestatus"));
                            list.add(game);
                        }
                        Message message=new Message();
                        message.what=0;
                        handler.sendMessage(message);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }


            }
        }).start();

//        queue= Volley.newRequestQueue(getActivity());
//        request=new StringRequest(Url.GETROAD + user_token, new Response.Listener<String>() {
//            @Override
//            public void onResponse(String s) {
//                Log.e("s",s);
//                String str= null;
//                try {
//                    str = new String(s.getBytes(),"GBK");
//                } catch (UnsupportedEncodingException e) {
//                    e.printStackTrace();
//                }
//                Log.e("str",str);
//                try {
//                    JSONObject jsonObject=new JSONObject(str);
//                    JSONObject jsonObject1=jsonObject.getJSONObject("data");
//                    JSONArray jsonArray=jsonObject1.getJSONArray("UserGameData");
//                    for (int i=0;i<jsonArray.length();i++){
//                        JSONObject jsonObject2=jsonArray.getJSONObject(i);
//                        Game game=new Game();
//                        game.setUserid(jsonObject2.getInt("userid"));
//                        game.setRoadid(jsonObject2.getInt("roadid"));
//                        game.setRoadname(jsonObject2.getString("roadname"));
//                        game.setDescription(jsonObject2.getString("description"));
//                        game.setPictureurl(jsonObject2.getString("pictureurl"));
//                        game.setInstid(jsonObject2.getString("instid"));
//                        game.setPreviousidxno(jsonObject2.getInt("previousidxno"));
//                        game.setNextidxno(jsonObject2.getInt("nextidxno"));
//                        game.setGroupid(jsonObject2.getString("groupid"));
//                        game.setNickname(jsonObject2.getString("nickname"));
//                        game.setSteps(jsonObject2.getInt("steps"));
//                        game.setActivestatus(jsonObject2.getInt("activestatus"));
//                        list.add(game);
//                    }
//                    if (adapter!=null){
//                        adapter.notifyDataSetChanged();
//                    }
//                    Message message=new Message();
//                    message.what=0;
//                    handler.sendMessage(message);
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//
//            }
//        }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError volleyError) {
//
//            }
//        });
//        queue.add(request);
//        HttpUtils utils=new HttpUtils();
//        utils.configCurrentHttpCacheExpiry(0);
//        utils.send(HttpRequest.HttpMethod.GET, Url.GETROAD + user_token, new RequestCallBack<String>() {
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//                String str=responseInfo.result.toString();
//                Log.e("str",str);
//                try {
//                    JSONObject jsonObject=new JSONObject(str);
//                    JSONObject jsonObject1=jsonObject.getJSONObject("data");
//                    JSONArray jsonArray=jsonObject1.getJSONArray("UserGameData");
//                    for (int i=0;i<jsonArray.length();i++){
//                        JSONObject jsonObject2=jsonArray.getJSONObject(i);
//                        Game game=new Game();
//                        game.setUserid(jsonObject2.getInt("userid"));
//                        game.setRoadid(jsonObject2.getInt("roadid"));
//                        game.setRoadname(jsonObject2.getString("roadname"));
//                        game.setDescription(jsonObject2.getString("description"));
//                        game.setPictureurl(jsonObject2.getString("pictureurl"));
//                        game.setInstid(jsonObject2.getString("instid"));
//                        game.setPreviousidxno(jsonObject2.getInt("previousidxno"));
//                        game.setNextidxno(jsonObject2.getInt("nextidxno"));
//                        game.setGroupid(jsonObject2.getString("groupid"));
//                        game.setNickname(jsonObject2.getString("nickname"));
//                        game.setSteps(jsonObject2.getInt("steps"));
//                        game.setActivestatus(jsonObject2.getInt("activestatus"));
//                        list.add(game);
//                    }
//                    Message message=new Message();
//                    message.what=0;
//                    handler.sendMessage(message);
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//
//            @Override
//            public void onFailure(HttpException e, String s) {
//
//            }
//        });
        return list;
    }
    public void getCity(){
        //声明AMapLocationClient类对象
        AMapLocationClient mLocationClient = null;
//声明定位回调监听器
        AMapLocationListener mLocationListener = new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation amapLocation) {
                if (amapLocation != null) {
                    if (amapLocation.getErrorCode() == 0) {
                        //定位成功回调信息，设置相关消息
                        amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                        amapLocation.getLatitude();//获取纬度
                        amapLocation.getLongitude();//获取经度
                        amapLocation.getAccuracy();//获取精度信息
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date date = new Date(amapLocation.getTime());
                        df.format(date);//定位时间
                        amapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                        amapLocation.getCountry();//国家信息
                        amapLocation.getProvince();//省信息
                        city=amapLocation.getCity();//城市信息
                        getWeather();
                        amapLocation.getDistrict();//城区信息
                        amapLocation.getStreet();//街道信息
                        amapLocation.getStreetNum();//街道门牌号信息
                        amapLocation.getCityCode();//城市编码
                        amapLocation.getAdCode();//地区编码
                    } else {
                        //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                        Log.e("AmapError", "location Error, ErrCode:"
                                + amapLocation.getErrorCode() + ", errInfo:"
                                + amapLocation.getErrorInfo());
                    }
                }
            }
        };
//初始化定位
        mLocationClient = new AMapLocationClient(getActivity());
//设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        AMapLocationClientOption mLocationOption = null;
//初始化定位参数
        mLocationOption = new AMapLocationClientOption();
//设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
//设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(true);
//设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
//设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
//设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
//给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
//启动定位
        mLocationClient.startLocation();
    }
    public void getWeather(){
        String str=city.substring(0,city.length()-1);
        WeatherSearchQuery weatherSearchQuery=new WeatherSearchQuery(str,WeatherSearchQuery.WEATHER_TYPE_LIVE);
        WeatherSearch weatherSearch=new WeatherSearch(getActivity());
        weatherSearch.setOnWeatherSearchListener(new WeatherSearch.OnWeatherSearchListener() {
            @Override
            public void onWeatherLiveSearched(LocalWeatherLiveResult weatherLiveResult, int rCode) {
                if (rCode == 0) {
                    if (weatherLiveResult != null && weatherLiveResult.getLiveResult() != null) {
                        weatherlive = weatherLiveResult.getLiveResult();
                        String tianqi=weatherlive.getWeather();
                        String temp= weatherlive.getTemperature();
                        textview.setText("天气:"+tianqi+" "+temp+"℃");
                        Log.e("weather", weatherlive.getWeather());

                    }else {

                    }
                }else {
                }
            }

            @Override
            public void onWeatherForecastSearched(LocalWeatherForecastResult localWeatherForecastResult, int i) {

            }
        });
        weatherSearch.setQuery(weatherSearchQuery);
        weatherSearch.searchWeatherAsyn();
        HttpUtils utils=new HttpUtils();
        utils.send(HttpRequest.HttpMethod.GET, Weatherurl + str, new RequestCallBack<Object>() {
            @Override
            public void onSuccess(ResponseInfo<Object> responseInfo) {
                Log.e("weather",responseInfo.result.toString());
                SAXParserFactory factory= SAXParserFactory.newInstance();
                try {
                    SAXParser parser=factory.newSAXParser();
                    parser.parse(getStringStream((String) responseInfo.result),new Saxserver());
                } catch (ParserConfigurationException e) {
                    e.printStackTrace();
                } catch (SAXException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });

//        RequestQueue queue= Volley.newRequestQueue(getActivity());
//        String str=city.substring(0,city.length()-1);
//        Log.e("str",str);
//        Log.e(Weatherurl+city,Weatherurl+str);
//           StringRequest stringRequest=new StringRequest(Weatherurl+str, new Response.Listener<String>() {
//               @Override
//               public void onResponse(String s) {
//                    Log.e("s",s);
//               }
//           }, new Response.ErrorListener() {
//               @Override
//               public void onErrorResponse(VolleyError volleyError) {
//
//               }
//           });
//           queue.add(stringRequest);
       }
    /**
     　　* 将一个字符串转化为输入流
     　　*/
    public InputStream getStringStream(String sInputString){
        if (sInputString != null && !sInputString.trim().equals("")){
            try{
                ByteArrayInputStream tInputStringStream = new ByteArrayInputStream(sInputString.getBytes());
                return tInputStringStream;
                }catch (Exception ex){
                ex.printStackTrace();
                }
            }
        return null;
    }
    class Saxserver extends DefaultHandler {
        @Override
        public void startDocument() throws SAXException {
            super.startDocument();
        }

        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            super.startElement(uri, localName, qName, attributes);
            tagname=localName;
        }

        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {
            super.endElement(uri, localName, qName);
        }

        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            super.characters(ch, start, length);
            if (tagname.equals("pm25")){
                pm25=new String(ch,start,length);
                Log.e("pm25", pm25);
            }if (tagname.equals("quality")){
                quality=new String(ch,start,length);
                Log.e("quality", quality);
                pmtextview.setText("PM:"+quality+" "+pm25);
            }
        }
    }



}
